// pages/delivery/manage.js
import {
  shops
} from '../../tools/shops';
import {
  dsx
} from '../../tools/datax';
import {
  ui
} from '../../tools/ui';
import {
  pages
} from '../../tools/pages';

Page({
  data: {
    list: [],
    shops: [],
    from: ''
  },
  onLoad(options) {
    this.setData({
      shops: shops.getShopObj(),
      from: options.from || ''
    });
    this.loadAddr()
  },

  useAddrTap(e) {
    const index = ui.eventData(e, 'index')
    ui.loading()
    this.saveAddrInUse(this.data.list, index).then(res => {
      ui.loading(false)
      ui.toast(res.result.errMsg.endsWith(':ok'), null, () => {
        pages.back(prePage => {
          prePage.selAddrCallback &&
            prePage.selAddrCallback(this.data.list, index)
        })
      })
    })
  },
  saveAddrInUse(list, index) {
    const addr = {
      ...list[index],
      list: undefined
    }
    return dsx.cloudUpdateWhere('delivery_addr', {
      _openid: true
    }, addr)
  },
  loadAddr() {
    ui.loading();
    dsx.cloudGetByOpenid('delivery_addr')
      .then(res => {
        const addr = res.result?.data[0] || {}
        const list = addr?.list || []
        this.setData({
          list,
          addr
        })

        return ui.loading(false)
      })
  },
  addrAddCallback() {
    this.loadAddr()
  },
  addrCellTap(e) {
    const index = ui.eventData(e, 'index')
    const addr = this.data.addr
    wx.navigateTo({
      url: `./edit/delivery?index=${index}&addrId=${addr._id}`,
    })
  },
  backTap() {
    pages.back();
  },
  addTap() {
    wx.navigateTo({
      url: './edit/delivery?action=add',
    })
  },
  onReady() {},
  onShow() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})